<template>
  <div style="width: 100%;height: 100%">
    <el-container v-if="initLoading" class="lab-design">
      <el-aside width="260px" class="lab-design-aside lab-design-left">
        <el-tabs v-model="leftActive">
          <el-tab-pane label="元组件" name="element">
            <div class="lab-design-aside-content">
              <template v-for="(item,index) in basicElements">
                <div v-if="item.level > 0" :key="index">
                  <div class="widget-cate">{{item.label}}</div>
                  <draggable tag="ul" :list="item.elements" :setData="()=>{}"
                             v-bind="{group:{ name:'people', pull:'clone',put:false},sort:false, ghostClass: 'ghost'}"
                             :move="() => {return true}"
                  >
                    <template v-for="(item, index) in item.elements">
                      <li v-if="!item.hidden" class="lab-design-item" :class="{'no-put': item.type === 'divider'}" :key="index">
                        <a>
                          <i class="icon iconfont" :class="item.icon" style="color: #409eff"></i>
                          <span>{{item.label}}</span>
                        </a>
                      </li>
                    </template>
                  </draggable>
                </div>
              </template>
            </div>
          </el-tab-pane>
<!--          <el-tab-pane label="视图模型" name="view" lazy>
            <div class="lab-design-aside-content">
              <el-input placeholder="视图搜索" suffix-icon="el-icon-search" v-model="search" clearable
                        @change="loadViewSource(viewDataSource, search)" style="margin-top: 4px" />

              <draggable tag="div" :list="viewDataSource" :setData="()=>{}"
                         v-bind="{group:{ name:'people', pull:'clone',put:false},sort:false, ghostClass: 'ghost'}"
                         :move="() => {return true}"
              >
                <template v-for="(item, index) in viewDataSource">
                  <el-card shadow="always" :key="index" :body-style="{ padding: '12px' }" class="lab-design-view">
                    <div slot="header">
                      <span>{{ item.label }}</span>
                    </div>
                    <div>
                      <div v-if="item.props" style="margin: -10px;font-size: 10px">
                        <div style="text-align: right"> {{ item.props.callCmd }}</div>
                      </div>
                      <span v-else>未知版本</span>
                    </div>
                  </el-card>
                </template>
              </draggable>
            </div>
          </el-tab-pane>-->
          <el-tab-pane label="组件树" name="tree">
            <element-tree :element="viewModel.element" />
          </el-tab-pane>
        </el-tabs>
      </el-aside>
      <el-container class="lab-design-main">
        <el-header height="38px" class="lab-design-header">
          <div class="lab-design-top">
            <div class="lab-top-left">
              <el-select v-if="view.callModel" v-model="element.props.modelType" placeholder="自动生成类型" @change="loadModel">
                <el-option value="form" label="表单"></el-option>
                <el-option value="table" label="表格"></el-option>
                <el-option value="manager" label="管理"></el-option>
              </el-select>
<!--              <el-input v-model="viewModel.callCmd" placeholder="调用指令" style="padding-right: 6px"></el-input>
              <el-input v-model="viewModel.viewName" placeholder="视图名称" style="padding-right: 6px"></el-input>
              <el-input v-model="viewModel.viewPrimary" placeholder="视图主键"></el-input>-->
            </div>
            <div class="lab-top-right">
              <el-button-group>
                <el-button type="primary" icon="el-icon-view" :loading="saveLoading" @click="()=>{labDesign.switch=false;previewVisible=true}">预览</el-button>
                <el-button type="success" icon="el-icon-tickets" :loading="saveLoading" @click="jsonVisible=true">结构</el-button>
<!--                <el-button type="info" icon="iconfont icon-form-setting" :loading="saveLoading" class="lab-button" @click="()=>{activeChange(viewModel,[],-1)}">设置</el-button>-->
                <el-button v-if="saveView" type="warning" icon="el-icon-check" :loading="saveLoading" @click="saveView(viewModel)">保存</el-button>
              </el-button-group>
            </div>
          </div>
        </el-header>
        <el-main>
          <lab-process :element="viewModel.element" :model-data="modelData" :showView="true" :process-info="{}" />
<!--          <lab-view :element="viewModel.element" :model-data="modelData" :showView="true" />-->
        </el-main>
      </el-container>
      <el-aside class="lab-design-aside lab-design-right" width="310px">
        <el-tabs v-model="rightActive">
          <template v-if="labDesign.activity.key && labDesign.activity.render">
            <el-tab-pane label="基础属性" name="attribute">
              <div class="lab-design-aside-content">
                <attribute />
              </div>
            </el-tab-pane>
<!--            <el-tab-pane v-if="['buttonGroup','table','tab','form','formTable'].includes(labDesign.activity.render)" label="子级管理" name="drag">
              <drag-attribute :element.sync="labDesign.activity" />
            </el-tab-pane>-->
            <template v-if="labDesign.renderItem">
              <el-tab-pane v-if="(labDesign.renderItem.actions && labDesign.renderItem.actions.length > 0 ) || (labDesign.renderItem.apis && labDesign.renderItem.apis.length > 0)" label="高级设置" name="event">
                <event-config :element.sync="labDesign.activity" />
              </el-tab-pane>
            </template>
          </template>
        </el-tabs>
      </el-aside>
    </el-container>

    <el-dialog :visible.sync="previewVisible" title="预览" width="90%" @close="() => {labDesign.switch=true}">
      <lab-process ref="viewRef" :element="viewModel.element" :model-data="modelData" :showView="true" :process-info="{}"  />
    </el-dialog>
    <el-dialog :visible.sync="jsonVisible" title="SCHEMA" width="80%">
      <lab-code v-model="viewModel.element" :config="{language: 'json'}" style="height: 80vh" />
    </el-dialog>
  </div>
</template>

<script>
import Draggable from 'vuedraggable'
import Attribute from "../../views/lab-design/attribute/Attribute";
import ElementTree from "../../views/lab-design/attribute/tree/ElementTree";
import EventConfig from "../../views/lab-design/attribute/EventConfig";
import LabProcess from "../lab-process/LabProcess";
import LabModel from "../../mixins/LabModel";
export default {
  name: "LabDesign",
  components: {LabProcess, EventConfig, ElementTree, Attribute, Draggable},
  mixins: [LabModel],
  props: {
    view: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  inject: {
    loadViewSource: {
      from: 'loadViewSource',
      default: function () {
        return function () {

        }
      }
    }
  },
  provide(){
    return {
      labDesign: this.labDesign,
    }
  },
  data() {
    return {
      labDesign:  { switch: true, activity: {}, index: -1, list: [], renderItem: {}, activeChange: this.activeChange },
      viewModel: { element: { render: 'form', elements: [], props: {}, label: '', mapper: '' } },
      leftActive: 'element',
      rightActive: 'attribute',
      previewVisible: false,
      jsonVisible: false,
      saveLoading: false,
      initLoading: false,
      search: '',
      viewDataSource: []
    }
  },
  watch: {
    leftActive() {
      if (this.leftActive === 'view') {
        this.loadViewSource(this.viewDataSource, this.search)
      }
    },
    previewVisible() {
      if (!this.previewVisible) {
        this.$Util.cleanObj(this, this.$refs.viewRef.registerMap)
        console.info('清空注册', this.$refs.viewRef.registerMap)
      }
    },
    /*'element.elements'() {
      const designForm = this.viewModel.element
      if (this.element.elements.length > 0) {
        designForm.elements.splice(0, designForm.elements.length)
        this.element.elements.forEach(item => {
          designForm.elements.push(item)
        })
        if (this.element.render === 'form') {
          designForm.requests = this.element.requests
          if (this.element.mapper) {
            designForm.mapper = this.element.mapper
          }
        }
      }
    }*/
  },
  created() {
    this.initLoading = false
    if (this.view.callModel) {
      this.$LabRender.autoFill(this.element, this)
      this.$set(this.element.props, 'callCmd',this.view.callModel)
      this.$set(this.element.props, 'modelType','')
    } else {
      this.$set(this.element.props, 'modelType','')
    }
    if (!this.$Util.isEmpty(this.view.callCmd)) {
      this.$set(this.viewModel.element.props, 'callCmd', this.view.callCmd)
    }
    this.$LabRender.autoFill(this.viewModel.element, this)
    setTimeout(() => {
      this.initLoading = true
    }, 200)
  },
  computed: {
    basicElements(){
      const levelSorts = this.$LabRender.list().sort((a, b) => a.level - b.level)
      let list = []
      levelSorts.forEach(item => {
        const levelObj = list.find(e => e.level === item.level)
        if (levelObj) {
          levelObj.elements.push(item)
        } else {
          list.push({
            level: item.level, label: item.type, elements: [ item ]
          })
        }
      })
      return list
    }
  },
  methods: {
    activeChange(item, elements, index) {
      if (!this.labDesign.switch) {
        return
      }
      this.labDesign.activity = item
      this.$set(this.labDesign.activity, 'expend', true)
      // this.$set(this.labDesign, 'activity', item)
      this.$set(this.labDesign, 'index', index)
      this.$set(this.labDesign, 'list', elements)
      this.$set(this.labDesign, 'renderItem', this.$LabRender.find(item.render))
      this.leftActive = 'tree'
      this.rightActive = 'attribute'

      /*setTimeout(() => {
        this.jupTree()
      }, 200)*/
    },
    jupTree() {
      const { activity } = this.labDesign
      // 树级容器
      const treeDom =  document.querySelector("#pane-tree .lab-design-aside-content")
      // 获取属性节点中的当前节点
      const activityDom = document.querySelector("#" + activity.key)
      const offsetHeight = treeDom.offsetHeight
      if (offsetHeight <= 0) {
        return
      }
      const height = offsetHeight / 2
      let top = 0
      if (activityDom.offsetTop > height) {
        // 小于整个高度
        if (activityDom.offsetTop < offsetHeight) {
          top = activityDom.offsetTop - height
        } else {
          // 大于整个高度
          top = activityDom.offsetTop - (activityDom.offsetTop / offsetHeight) * offsetHeight + height
        }
      }
      console.info(activityDom.offsetTop, top, treeDom.scrollHeight, offsetHeight)
      treeDom.scrollTo({
        top: top,
        behavior: "smooth"
      })
    },
    saveView(viewModel){
      this.saveLoading = true
      console.info('保存视图', viewModel, this.view)
      this.view.element = viewModel.element
      this.$post('/view/save', this.view)
          .then(res => {
            this.$resultMsg(this, res)
            if (res.code === 200) {
              this.$emit('save')
            }
            setTimeout(() => {
              this.saveLoading = false
            }, 200)
          })
    },
    modelCallBack(element) {
      const designForm = this.viewModel.element
      if (element.elements.length > 0) {
        designForm.elements.splice(0, designForm.elements.length)
        element.elements.forEach(item => {
          designForm.elements.push(item)
        })
        if (element.render === 'form') {
          designForm.requests = element.requests
          if (element.mapper) {
            designForm.mapper = element.mapper
          }
          const { rowKey } = element.props
          if (rowKey) {
            designForm.props.rowKey = rowKey
          }
        }
      }
    }
  }
}
</script>
